package org.example.backend.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.backend.common.Result;
import org.example.backend.dto.EmailDTO;
import org.example.backend.dto.EmailLoginDTO;
import org.example.backend.dto.LoginDTO;
import org.example.backend.dto.LoginResponseDTO;
import org.example.backend.dto.RegisterDTO;
import org.example.backend.entity.User;
import org.example.backend.service.AdminService;
import org.example.backend.service.EmailService;
import org.example.backend.service.UserService;
import org.example.backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@Api(tags = "认证接口")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private EmailService emailService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     *
     * @param loginDTO 登录参数
     * @return 登录结果
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<?> login(@Valid @RequestBody LoginDTO loginDTO) {
        try {
            // 根据角色判断是用户登录还是管理员登录
            if ("USER".equals(loginDTO.getRole())) {
                return Result.success(userService.login(loginDTO));
            } else {
                return Result.success(adminService.login(loginDTO));
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 邮箱验证码登录
     *
     * @param emailLoginDTO 邮箱登录参数
     * @return 登录结果
     */
    @PostMapping("/emailLogin")
    @ApiOperation("邮箱验证码登录")
    public Result<?> emailLogin(@Valid @RequestBody EmailLoginDTO emailLoginDTO) {
        try {
            // 验证验证码
            boolean verified;
            try {
                verified = emailService.verifyCode(emailLoginDTO.getEmail(), emailLoginDTO.getCode());
            } catch (Exception e) {
                return Result.error(e.getMessage());
            }
            
            // 根据邮箱查询用户
            if ("USER".equals(emailLoginDTO.getRole())) {
                // 查询用户是否存在
                User user = userService.getByEmail(emailLoginDTO.getEmail());
                if (user == null) {
                    return Result.error("该邮箱未注册");
                }
                
                // 直接构造登录响应，不进行密码验证
                LoginResponseDTO responseDTO = new LoginResponseDTO();
                responseDTO.setUserId(user.getId());
                responseDTO.setUsername(user.getUsername());
                responseDTO.setRole("USER");
                responseDTO.setEmail(user.getEmail());
                responseDTO.setPhone(user.getPhone());
                responseDTO.setAddress(user.getAddress());
                
                // 生成token
                String token = jwtUtil.generateToken(user.getId(), user.getUsername(), "USER");
                responseDTO.setToken(token);
                
                return Result.success(responseDTO);
            } else {
                return Result.error("邮箱验证码登录仅支持用户角色");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户注册
     *
     * @param registerDTO 注册参数
     * @return 注册结果
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result<?> register(@Valid @RequestBody RegisterDTO registerDTO) {
        try {
            userService.register(registerDTO);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 发送验证码
     *
     * @param emailDTO 邮箱参数
     * @return 发送结果
     */
    @PostMapping("/sendCode")
    @ApiOperation("发送验证码")
    public Result<?> sendCode(@Valid @RequestBody EmailDTO emailDTO) {
        try {
            emailService.sendVerificationCode(emailDTO.getEmail());
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 验证验证码
     *
     * @param emailDTO 邮箱参数
     * @return 验证结果
     */
    @PostMapping("/verifyCode")
    @ApiOperation("验证验证码")
    public Result<?> verifyCode(@Valid @RequestBody EmailDTO emailDTO) {
        try {
            boolean result = emailService.verifyCode(emailDTO.getEmail(), emailDTO.getCode());
            // 验证成功
            return Result.success("验证码验证成功");
        } catch (Exception e) {
            // 验证失败，返回具体错误信息
            return Result.error(e.getMessage());
        }
    }
}
